package com.sc.byahi.user.client;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.logging.Logger;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.sc.byahi.user.client.components.SummaryPager;
import com.sc.byahi.user.shared.Profile;
import com.sc.byahi.user.shared.SharedUtil;
import com.sc.byahi.user.shared.constants.Config;

public class SummaryListView extends Composite implements ICleaner {
	private static final Logger logger = Logger.getLogger("com.sc.byahi.user.client.SummaryListView");
	private VerticalPanel vertPanel = new VerticalPanel();
	private HTML currprofileText = new HTML();
	private Anchor idAnchor = new Anchor();
	private DisclosurePanel currentProfilePanel = new DisclosurePanel("Click here to change your current profile ID.");
	private SummaryPager pagerView;
	private FlexTable summaryTable = new FlexTable();

	protected Map<Long, Map<String, Set<Long>>> data = new HashMap<Long, Map<String, Set<Long>>>();
	boolean isUser = false;

	
	public SummaryListView() {
		initWidget(vertPanel);
		addHandlers();
	}

	private void addHandlers() {
		idAnchor.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				String id = idAnchor.getText();
				Long pid = SharedUtil.getLong(id);
				if(pid == null){
					UIUtil.showDialog(Arrays.asList("There is some error with this profile ID. Please check it again and make sure this ID belongs to you."), "Wrong profile data");
				}else{
					showProfile(pid);
				}
			}
		});
		currentProfilePanel.addOpenHandler(new OpenHandler<DisclosurePanel>() {
			@Override
			public void onOpen(OpenEvent<DisclosurePanel> event) {
				final FlexTable tab = new FlexTable();
				tab.setStyleName("profile-display-label");

				final TextBox pid = new TextBox();
				final Button pidSubmit = new Button("Click here to change curent profile ID.");

				int row = 0;

				tab.setWidget(row++, 0, new HTML("Please enter profile id to be set as current profile id."));
				tab.setWidget(row++, 0, pid);
				tab.setWidget(row++, 0, pidSubmit);

				pidSubmit.addClickHandler(new ClickHandler() {

					@Override
					public void onClick(ClickEvent event) {
						Long p = SharedUtil.getLong(pid.getText().trim());
						if (p != null) {
							if(AppController.get().getOwner().getAllProfiles().contains(p)){
								AppController.get().setCurrentProfileId(p);
								setCurrProfileText();
							}else{
								UIUtil.showDialog(Arrays.asList("There is some error with this profile ID. Please check it again and make sure this ID belongs to you."), "Wrong profile data");
							}
						}
					}
				});

				currentProfilePanel.setContent(tab);
			}
		});
	}
	
	/**
	 * This one cleans old data also.
	 * 
	 * @param data
	 */
	public void setData(Map<Long, Map<String, Set<Long>>> data, boolean isUser) {
		clean();// Should call subclass method
		if (data != null)
			this.data = data;
		this.isUser = isUser;
		setCurrProfileText();
		redrawView();
	}
	
	public void setCurrProfileText(){
		Long currProfileId = AppController.get().getCurrentProfileId();
		if(currProfileId != null){
			idAnchor.setVisible(true);
			idAnchor.setText(currProfileId.toString());
			currprofileText.setHTML("You are working on behalf of " + AppController.get().getCurrentProfileName()+ " ( ID: " + currProfileId + " ). Whatever interests or messages you send, will be sent by this user." +
					"You can change it by clicking the link below. Also it will change automatically when you click a profile from the summary below (you will see it next to logout button on top-right corner.)");
		}else{
			idAnchor.setVisible(false);
			currprofileText.setHTML("You don't have any approved profile yet, please wait for your profiles to be approved to start sending and receiving messages.");
		}
	}

	/**
	 * Recreates whole view, including paginator part
	 */
	public void redrawView() {
//		clean();
		pagerView = new SummaryPager(data, isUser, this);
		fillVPanel();
		redrawTablePage();
	}

	private void fillVPanel() {
		vertPanel.add(idAnchor);
		vertPanel.add(currprofileText);
		vertPanel.add(currentProfilePanel);
		vertPanel.add(new HTML("<hr>"));
		vertPanel.add(pagerView);
		vertPanel.add(summaryTable);
	}

	public void redrawTablePage() {
		summaryTable.clear();
		List<Entry<Long, Map<String, Set<Long>>>> currIds = pagerView.getPage();
		if(Config.summaryViewType == 1){
			int index = 0;
			for (Entry<Long, Map<String, Set<Long>>> entry : currIds) {
				Summary sumaryView = new Summary();
				summaryTable.setWidget(index++, 0, sumaryView);
				sumaryView.setData(entry);
			}
		}else if(Config.summaryViewType == 2){
			SummaryLine sumaryView = new SummaryLine();
			sumaryView.setData(currIds);
			summaryTable.setWidget(0, 0, sumaryView);
		}
	}

	/*
	@Deprecated
	private void setProfileView(final FlexTable tab, final int index, Long profileId) {
		GreetingService.Util.getInstance().findMyProfilesById(Arrays.asList(profileId), new AsyncCallback<List<Profile>>() {

			@Override
			public void onSuccess(List<Profile> result) {
				if (!result.isEmpty()) {
					Profile p = result.get(0);
					AppController.get().setCurrProfileId(p.getId());
					ProfileViewDiv profileViewDiv = new ProfileViewDiv();
					profileViewDiv.setOwnData(true);// so that no button appears here
					profileViewDiv.showData(p);
					tab.setWidget(index, 0, profileViewDiv);
				} else {
					tab.setWidget(index, 0, new Label("There is some error with this profile ID. Please check it again and make sure this ID belongs to you."));
				}
			}

			@Override
			public void onFailure(Throwable caught) {
			}
		});
	}
	*/
	private void showProfile(final Long profileId) {
		GreetingService.Util.getInstance().findMyProfilesById(Arrays.asList(profileId), new AsyncCallback<List<Profile>>() {

			@Override
			public void onSuccess(List<Profile> result) {
				if (!result.isEmpty()) {
					Profile p = result.get(0);
					ProfileViewDiv profileViewDiv = new ProfileViewDiv();
					profileViewDiv.setOwnData(true);
					profileViewDiv.setReadOnly(true);
					profileViewDiv.showData(p);
					UIUtil.showDialog(profileViewDiv);
				} else {
					UIUtil.showDialog(Arrays.asList("There is some error with this profile ID. Please check it again and make sure this ID belongs to you."), "Wrong profile data");
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				UIUtil.showGenericFailureDialog();

			}
		});
	}

	@Override
	public void clean() {
		vertPanel.clear();
	}

}
